package com.threadPool.thread;

import com.threadPool.pool.BaseThreadPool;
import com.threadPool.pool.DynamicThreadPoolManager;
import com.threadPool.pool.MyThreadPool;

import java.util.concurrent.BlockingDeque;

public class CoreThread extends Thread{
    private BlockingDeque<Runnable> taskQueue;
    private volatile boolean isStopped = false;
    public CoreThread(BlockingDeque<Runnable> taskQueue) {
        this.taskQueue = taskQueue;
    }

    public CoreThread() {
    }

    public CoreThread createThread(BlockingDeque<Runnable> taskQueue) {
        return new CoreThread(taskQueue);
    }
    public void stopThread() {
        isStopped = true;
        this.interrupt(); // 中断阻塞状态
    }
    @Override
    public void run() {
        BaseThreadPool myThreadPool = DynamicThreadPoolManager.getInstance().getMyThreadPool();
        Throwable thrown = null; // 新增异常变量
        while (!isStopped || !taskQueue.isEmpty()) {
            Thread currentThread = Thread.currentThread();
            Runnable task = null;
            try {
                Runnable take = taskQueue.take();
                // 调用前记录
                task = take;
                myThreadPool.beforeExecute(currentThread, task);
                take.run();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 重新设置中断状态
                thrown = e; // 记录中断异常
                break; // 退出循环
            } catch (Throwable t) { // 捕获其他异常
                thrown = t;
                // 保留原有异常处理逻辑
            } finally {
                // 调用后记录（即使发生异常）
                myThreadPool.afterExecute(task, thrown);
            }
        }
    }
}
